package SqlJavaBean;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.Statement;

public class RunSql {
	private Connection connect;
	
	public RunSql(Connection con){
		connect = con;
	}
	
	public String runSql(String sql){
		ResultSet rs;
		String res = "";
		try
		{
			Statement state = connect.createStatement();
			boolean hasReaSet = state.execute(sql);
			if(hasReaSet) {
				rs = state.getResultSet();
				return setRes(rs);
			}
			else res = " SQL 命令执行成功！";
		}
		catch(Exception e)
		{
			res = e.getMessage();
			System.out.println(res);
		}
		return res;
	}
	private String setRes(ResultSet rs){  //此处unicode码为安卓端处理数据提供标识
		String res = "";
		try
		{
			ResultSetMetaData d = rs.getMetaData();
			int cols = d.getColumnCount();
			for(int i=0;i<cols;i++){
				res = res+d.getColumnName(i+1)+"\t\u0005";
			}
			res+="\n\n\u0006";
			while(rs.next()){
				for(int i=0;i<cols;i++){
					res = res+rs.getString(i+1)+"\t\u0005";
				}
				res+="\n\u0006";
			}
		}
		catch(Exception e){
			res = res +"\n"+e.getMessage();
		}
		return res;
	}
	public boolean loadData(String file,String tableName){ // 批量导入数据
		String[] record = file.split("\u0001");
		int len = record[0].split("\t").length;
		String wenhao = "";
		while(len-->1) wenhao = wenhao+"?,";
		wenhao = wenhao +"?)";
		String sql = "insert into "+tableName+" values("+wenhao;
		try{
			PreparedStatement insert = connect.prepareStatement(sql);
			for(String s:record){
				String[] data = s.split("\t");
				for(int i=0;i<data.length;i++) insert.setString(i+1,data[i]);
				insert.executeUpdate();
			}
			return true;
		}
		catch(Exception e){
			String res = "导入数据失败！"+e.getMessage();
		}
		return false;
	}
}
